<?php

namespace app\index\controller\business;

use app\common\controller\Index;

/**
 * 客户中心控制器
 */ 
class Business extends Index{
    protected $noNeedLogin = ['*'];

    // 继承父类，构造函数
    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('Subject.Order');

        $this->RecordModel = model('Business.Record');

        $this->SubjectModel = model('Subject.Subject');

        $this->CommentModel = model('Subject.Comment');

        $this->ListsModel = model('Subject.Lists');
    }

    //客户中心
    public function index(){
        return $this->view->fetch();
    }
    // 个人资料
    public function profile(){

        if($this->request->isPost()){
            // 取值
            $nickname = $this->request->param('nickname', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '', 'trim');
            $region = $this->request->param('region', '', 'trim');
            // 空数组整合数据
            $data_info = [
                'id' =>cookie('LoginUser')['id'],
                'nickname' => $nickname,
                'gender' => $gender,
                'region' => $region,
            ];
            if(!empty($password)){
                $oldsalt = $this->loginAuth['salt'];
                $newpass = md5($password.$oldsalt);
                $oldpass = $this->loginAuth['password'];
                if($newpass == $oldpass){
                    $this->error('新的密码不能重复');
                    exit;
                }

                $salt = build_ranstr();
                $password = md5($password.$salt);
                $data_info['password'] = $password;
                $data_info['salt'] = $salt;
            }

            if(!empty($region)){
                $region = explode('/',$region);
                $data_info['province'] = isset($region['0']) ? trim($region['0']) : '';
                $data_info['city'] = isset($region['1']) ? trim($region['1']) : '';
                $data_info['district'] = isset($region['2']) ? trim($region['2']) : '';
            }

            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0){
                var_dump('123');
                exit;
            }
            exit;

            $sql = $this->BusinessModel->isUpdate(true)->save($data_info);

            if($sql == false){
                $this->error($this->BusinessModel->getError());
                exit;
            }

            $login = [
                'id' => cookie('LoginUser')['id'],
                'mobile' => cookie('LoginUser')['mobile'],
                'nickname' => $data_info['nickname'],
                'avatar' => cookie('LoginUser')['avatar'],
                'deal' => cookie('LoginUser')['deal'],
            ];
            cookie('LoginUser',$login);
            $this->success('更新资料成功','/index/index/index');
            exit;

        }

        $user_id = cookie('LoginUser')['id']?cookie('LoginUser')['id']:0;
        $user_mobile = cookie('LoginUser')['mobile']?cookie('LoginUser')['mobile']:'';
        $where = [
            'id' => $user_id,
            'mobile' => $user_mobile,
        ];
        $sql = $this->BusinessModel->where($where)->select();
        if(!$sql){
            cookie('LoginUser',null);
            $this->error('登录信息有误','index/index/login');
            exit;
        }
        $user = $sql;
        $user = collection($user)->toArray();
        $user = isset($user['0'])?$user['0']:[];
        $province = $user['province'];
        $city = $user['city'];
        $district = $user['district'];
        $address = $province.'/'.$city.'/'.$district;
        $user['address'] = $address;

        $this->view->assign('user',$user);
        return $this->view->fetch();
    }
    // 订单记录/消费记录
    public function order(){

        $user_id = cookie('LoginUser')['id']?cookie('LoginUser')['id']:0;
        $user_mobile = cookie('LoginUser')['mobile']?cookie('LoginUser')['mobile']:'';
        
        $where = [
            'id' => $user_id,
            'mobile' => $user_mobile,
        ];

        $sql = $this->BusinessModel->where($where)->select();
        if(!$sql){
            cookie('LoginUser',null);
            $this->error('登录信息有误','index/index/login');
            exit;
        }
        
        $order_booler = true;

        $order_list = $this->OrderModel->with('subject')->where(['busid'=>$user_id])->select();
       
        // $subid = [];
        // foreach($order as $key=>$item){
        //     $subid[] += $item['subid'];
        // }
        // $subject_list = [];
        // foreach($subid as $item){
        //     $subject = $this->OrderModel->subject()->where(['id'=>$item])->select();
        //     $subject = collection($subject)->toArray();
        //     $subject = isset($subject[0])?$subject[0]:[];
        //     $subject_list[] = $subject;
        // }
        // var_dump($subject_list);
        // var_dump($order);
        
        // exit;
        // $subject_list = $this->OrderModel->where([->$order_list['subid']])->select();
        $order_msg = '';
        if(!$order_list){
            $order_msg = '当前无视频购买记录';
        }

        // 获取课程名称和课程简介
        // $order = collection($order_list)->toArray();
        // $order = isset($order['0'])?$order['0']:[];
        // $subid = $order['subid'];
        // $sql = $this->SubjectModel->where(['id'=>$subid])->select();
        // $subject_list = $sql;
        // $subject_list = collection($subject_list)->toArray();
        // $subject_list = isset($subject_list[0])?$subject_list[0]:[];
        // $subject_title = $subject_list['title'];
        // $subject_content = $subject_list['content'];
        // $order['subject_title'] = $subject_title;
        // $order['subject_content'] = $subject_content;

        // 将购买课程时间戳转换为字符串


        $sql = $this->RecordModel->where(['busid'=>$user_id])->select();

        $record_list = $sql;
        $record_msg = '';
        if(!$record_list){
            $record_msg = '当前无消费记录';
        }

        if($this->request->isAjax()){
            if($this->request->param('action') == 'order'){
                $order_booler = true;
                $this->success('获取order表成功','',$order_booler);
            }else{
                $order_booler = false;
                $this->success('获取record表成功','',$order_booler);
            }
        }
        $this->view->assign([
            'order_booler' => $order_booler,
            'order_list' => $order_list,
            'record_list' => $record_list,
            'order_msg' => $order_msg,
            'record_msg' => $record_msg,
        ]);
        return $this->view->fetch();


    }
    // 联系我们
    public function contact(){
        // 课程分级顺序
        $CategoryModel = model('Subject.Category');
        $cate = $CategoryModel->order("weight ASC")->select();
        $cate = collection($cate)->toArray();
        // 轮播图循环顺序
        $SubjectModel = model('Subject.Subject');
        $toplist = $SubjectModel->orderRaw("LPAD(LOWER(likes),10,0)DESC")->select();
        $toplist = collection($toplist)->toArray();
        
        $catelist = [];
        // 将分级课程循环一遍拿到id
        foreach($cate as $key=>$item){

            // 左联拿到课程数据
            $subject = $SubjectModel->where(['cateid'=>$item['id']])->order('createtime DESC')->select();
            $subject = collection($subject)->toArray();

            // 有课程才追加分类
            if($subject){
                $catelist[] = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'subject' => $subject,
                ];
            }
        }
        $this->view->assign([
            'catelist' => $catelist,
            'toplist' => $toplist,
        ]);


        return $this->view->fetch();
    }
    public function analysis(){
        // 课程分级顺序
        $CategoryModel = model('Subject.Category');
        $cate = $CategoryModel->order("weight ASC")->select();
        $cate = collection($cate)->toArray();
        // 轮播图循环顺序
        $SubjectModel = model('Subject.Subject');
        $toplist = $SubjectModel->orderRaw("LPAD(LOWER(likes),10,0)DESC")->select();
        $toplist = collection($toplist)->toArray();
        
        $catelist = [];
        // 将分级课程循环一遍拿到id
        foreach($cate as $key=>$item){

            // 左联拿到课程数据
            $subject = $SubjectModel->where(['cateid'=>$item['id']])->order('createtime DESC')->select();
            $subject = collection($subject)->toArray();

            // 有课程才追加分类
            if($subject){
                $catelist[] = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'subject' => $subject,
                ];
            }
        }
        $this->view->assign([
            'catelist' => $catelist,
            'toplist' => $toplist,
        ]);

        return $this->view->fetch();
    }
    public function comment($subid = 0){
        if($this->request->isGet()){
            $subid = $this->request->param('subid');
            $sql = $this->SubjectModel->where(['id'=>$subid])->select();
            $subject = $sql;
            if(!$subject){
                $this->error('无法找到当前课程','/index/business/Business/order');
            }
            $subject = isset($subject[0])?$subject[0]:[];
            $this->view->assign([
                'subid'=>$subid,
                'title'=>$subject['title'],
                'thumbs'=>$subject['thumbs'],
            ]);

        }

        if($this->request->isPost()){
            $level = $this->request->param('level',5,'');
            $content = $this->request->param('answerParse','','trim');

            if(!$content){
                $this->error('当前评论字段为空','/index/business/Business/order');
                exit;
            }

            $user_id = cookie('LoginUser')['id']?cookie('LoginUser')['id']:0;
            if(!$user_id){
                cookie('LoginUser',null);
                $this->error('无当前用户，请重新登录','/index/index/login');
                exit;
            }

            $subid = $this->request->param('subid',0,'');
            if(!$subid){
                $this->error('当前课程获取错误，请重试','/index/business/Business/order');
                exit;
            }

            $sql = $this->ListsModel->where(['subid'=>$subid])->select();
            $lists_list = collection($sql)->toArray();
            $list_id = [];
            foreach($lists_list as $item){
                $list_id[] = $item['id'];
            }
            $list_id = isset($list_id[0])?$list_id[0]:0;

            // 准备更新
            $data = [
                'level' => $level,
                'content' => $content,
                'busid' => $user_id,
                'listid' => $list_id,
            ];
            $sql = $this->CommentModel->data($data)->save();
            if(!$sql){
                $this->error($this->CommentModel->getError());
                exit;
            }
            $this->success('评论成功','/index/business/Business/order');
        }
        return $this->view->fetch();
    }
    public function analysis_echarts(){
        if($this->request->isAjax()){
            $user_id = isset(cookie('LoginUser')['id'])?cookie('LoginUser')['id']:0;
            if(!$user_id){
                cookie('LoginUser',null);
                $this->error('无用户id，重新登录');
                exit;
            }

            $sql = $this->RecordModel->where(['busid'=>$user_id])->order('createtime desc')->select();
            $record_list = $sql;
            if(!$record_list){
                $this->error('当前没有消费记录');
                exit;
            }
            $record_list = collection($record_list)->toArray();

                // 将获取订单中，最大的一年（例2022），加一年（2023），中间的12个月份循环获取时间戳
                $year_min = isset($record_list[0]['createtime'])?date('Y',$record_list[0]['createtime']):'';
                $time_year  = mktime(0, 0, 0, 1,1, $year_min);//1640966400
                $year_max = $year_min+1;
                $time_year_max = (mktime(0, 0, 0, 1,1, $year_max))-2628000;//1672502400
                $month = ($time_year_max-$time_year)/11;//2628000
                $month_list_im = [];
                $month_list_stamp = [];
                for($i=$time_year;$i<=$time_year_max;$i+=$month){
                    $month_list_im[] = date('m',$i);
                    $month_list_stamp[] = $i;
                }

                // 查询消费记录
                // 根据日期查出表中同一个月的账单
                $month_total = [];
                foreach($month_list_stamp as $stamp){
                    $month_ul = date('Y-m',$stamp);
                    $stamp_sql = $this->RecordModel->where('createtime','between time',[$stamp,$stamp+$month])->where(['busid'=>$user_id])->field('total')->select();
                    if($stamp_sql){
                        $stamp_sql = collection($stamp_sql)->toArray();
                    }
                    $month_total[$month_ul] = $stamp_sql;
                };

                // 将同一个月内的账单做总和（无账单则跳过）
                $record_total = [];
                foreach($month_total as $key=>$item){
                        $item = array_sum(array_column($item,'total'));
                        $record_total[$key] = $item;
                }

                // 查询购买记录
                foreach($month_list_stamp as $stamp){
                    $month_ul = date('Y-m',$stamp);
                    $stamp_sql = $this->OrderModel->where('createtime','between time',[$stamp,$stamp+$month])->where(['busid'=>$user_id])->field('total')->select();
                    if($stamp_sql){
                        $stamp_sql = collection($stamp_sql)->toArray();
                    }
                    $month_total[$month_ul] = $stamp_sql;
                };

                // 将同一个月内的账单做总和（无账单则跳过）
                $order_total = [];
                foreach($month_total as $key=>$item){
                        $item = array_sum(array_column($item,'total'));
                        $order_total[$key] = $item;
                }
                $month_list_im = (implode("月,",$month_list_im))."月";
                $record_total = implode(',',$record_total).',0';
                $order_total = implode(',',$order_total).',0';
                $month_list_im = explode(',',$month_list_im);
                $order_total = explode(',',$order_total);
                $record_total = explode(',',$record_total);
            $this->success('获取数据成功',null,[
                'month'=>$month_list_im,
                'year_min'=>$year_min,
                'record_total'=>$record_total,
                'order_total'=>$order_total,
            ]);

        }
    }
}
// 外网面板地址: http://43.139.5.64:8888/b657e3c3
// 内网面板地址: http://10.0.12.7:8888/b657e3c3
// *以下仅为初始默认账户密码，若无法登录请执行bt命令重置账户/密码登录
// username: 1btuugj3
// password: 7SZfgGXzxGWP
